package com.tgpms.web.earlierStage.service.impl;

import com.tgpms.web.earlierStage.entity.DocUploadEntity;
import com.tgpms.web.earlierStage.entity.DocUploadEntityHistory;
import com.tgpms.web.earlierStage.dao.DocUploadEntityHistoryMapper;
import com.tgpms.web.earlierStage.dao.DocUploadEntityMapper;
import com.tgpms.web.earlierStage.service.IDocUploadEntityHistoryService;
import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.UUID;
import java.util.Date;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.util.Common;
import com.tgpms.util.FTPUtil;

/**
 * <p>
 * 文档版本信息表 服务实现类
 * </p>
 *
 * @author newway
 * @since 2020-04-07
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class DocUploadEntityHistoryServiceImpl implements IDocUploadEntityHistoryService {

	@Resource
	private DocUploadEntityHistoryMapper mapper;
	@Resource
	private DocUploadEntityMapper docUploadEntityMapper;

	//ftp_url
	@Value("${ftpparam.url}")
	private String url;
	@Value("${ftpparam.port}")
	private Integer port;
	@Value("${ftpparam.username}")
	private String username;
	@Value("${ftpparam.password}")
	private String password;
	@Value("${ftpparam.downurl}")
	private String downurl;
	@Value("${ftpparam.filepath3}")
	private String filepath3;
	@Value("${ftpparam.localloadfile}")
	private String localloadfile;

	/**
		新增文档版本信息表
	 */
	@Override
	public Result addDocUploadEntityHistory(DocUploadEntityHistory en,Result result,MultipartFile file) throws Exception{
		String id = Common.fromDateFormats()+UUID.randomUUID().toString().replaceAll("-", "");
		en.setId(id);
		en.setRowstamp(id);
		//查询当前文件最大版本号
		Integer version = mapper.getMaxVersionByDocId(en.getDocId());
		if(version==null) {
			version = 1;
		}else {
			version = version+1;
		}
		en.setDocVersion(version);
		//处理中文文件名乱码
		String ndocName = Common.getUTFStringByEncoding(en.getDocName());
		String docName = ndocName;
		//获取当前上传人
		String nuser = en.getUploadUser();
		//将现文件信息放入文档版本实体
		DocUploadEntity doc = docUploadEntityMapper.selectByPrimaryKey(en.getDocId());
		en.setFileSize(doc.getFileSize());
		en.setDocName(doc.getDocName());
		en.setFilePath(doc.getFilePath());
		en.setNewDocName(doc.getNewDocName());
		en.setUploadDate(doc.getUploadDate());
		en.setUploadUser(doc.getUploadUser());
		//获取文件大小
		Long fileSize = file.getSize();
		//指定存放上传文件的临时目录
		String fileDir = localloadfile;
		File dir = new File(fileDir);
		//判断目录是否存在，不存在则创建目录
		if (!dir.exists()){
			dir.mkdirs();
		}
		// 获取文件后缀
		String suffix=(docName.substring(docName.lastIndexOf(".")+1)).toLowerCase();
		String newfileName = "qqgl"+Common.fromDateFormat("yyyyMMddHHmmssSSS");
		docName = newfileName+"."+suffix;
		File excelFile = new File(dir.getAbsolutePath()+ File.separator+ docName);
		file.transferTo(excelFile);
		int i = mapper.insert(en);
		if(i==1) {
			//更新文档信息表
			doc.setId(en.getDocId());
			doc.setDocName(ndocName);
			doc.setFilePath(filepath3);
			doc.setFileSize(fileSize);
			doc.setNewDocName(docName);
			doc.setModifyDate(new Date());
			doc.setModifyUser(nuser);
			i = docUploadEntityMapper.updateByPrimaryKeySelective(doc);
			if(i==1) { 
				result.setData(id);
				result.setMsg(ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
			}else {
				result.setSuccess(false);
				result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
			}
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		}
		return result;
	}

	/**
		更新文档版本信息表
	 */
	@Override
	public Result updateDocUploadEntityHistory(DocUploadEntityHistory en,Result result) {
		int i = mapper.updateById(en);
		if(i==1) {
			result.setMsg(ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
		}
		return result;
	}

	/**
		根据主键删除文档版本信息表
	 */
	@Override
	public Result deleteDocUploadEntityHistory(Serializable id,Result result) {
		DocUploadEntityHistory en = new DocUploadEntityHistory();
		int i = mapper.deleteById(id);
		if(i==1) {
			//删除文件
			if(en!=null) {
				String fileDir = localloadfile;
				File dir = new File(fileDir);
				if (!dir.exists()){
					dir.mkdirs();
				}
				File excelFile = new File(dir.getAbsolutePath()+ File.separator+ en.getNewDocName());
				if(excelFile.exists()) {
					excelFile.delete();
				}
				FTPUtil.deleteFile(url, port, username, password, en.getFilePath(), en.getNewDocName());
			}
			result.setMsg(ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
		}else {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
		}
		return result;
	}

	@Override
	public ResponseEntity<byte[]> downHistoryDoc(Serializable id,InputStream in,ResponseEntity<byte[]> entity) 
			throws Exception {
		DocUploadEntityHistory his = mapper.selectById(id);
		if(his!=null) {
			//先从本地文件夹取文件，有则本地下载，无则ftp下载
			String fileDir = localloadfile;
			File dir = new File(fileDir);
			if (!dir.exists()){
				dir.mkdirs();
				in = FTPUtil.downloadFileForIn(url, port, username, password, his.getFilePath(), his.getNewDocName());
			}else {
				File excelFile = new File(dir.getAbsolutePath()+ File.separator+ his.getNewDocName());
				if(excelFile.exists()) {
					in = new FileInputStream(excelFile);
				}else {
					in = FTPUtil.downloadFileForIn(url, port, username, password, his.getFilePath(), his.getNewDocName());
				}
			}
			//设置浏览器响应
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", his.getDocName());
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			HttpStatus status = HttpStatus.OK;
			//返回字节流IOUtils.toByteArray(in)
			entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, status);
		}
		return entity;
	}
}
